<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="请输入部门名称或编号" clearable @clear="flush"></el-input>
				</el-form-item>
				<el-form-item>
                    <!--查询携带从第一页开始查的条件-->
					<el-button type="primary" v-on:click="handleCurrentChange(1)">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table ref="deptTable" @select="selectRow" :data="departments" highlight-current-row v-loading="listLoading" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="120" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable>
			</el-table-column>
            <el-table-column prop="dirPath" label="层级路径" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="90" sortable>
                <template scope="scope">
                    <span v-if="scope.row.state==0" style="color: #18c79c">启用</span>
                    <span v-else-if="scope.row.state==-1" style="color: #ff4d51">禁用</span>
                    <span v-else style="color: #8c939d">未知</span>
                </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" min-width="120" sortable>
			</el-table-column>
            <el-table-column prop="parent.name" label="上级部门" min-width="120" sortable>
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel( scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" v-perm="'department:batchRemove'">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增&编辑界面-->
		<el-dialog :title=title :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
                <el-form-item label="部门编号" prop="sn">
                    <el-input v-model="addForm.sn" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="addForm.state">
                        <el-radio class="radio" :label="0">启用</el-radio>
                        <el-radio class="radio" :label="-1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            <el-form-item label="部门经理">
                <el-select v-model="addForm.manager.id" placeholder="请选择部门经理">
                    <el-option
                            v-for="item in employees"
                            :key="item.id"
                            :label="item.username"
                            :value="item.id">
                        <span style="float: left">{{ item.username }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
                <el-form-item label="所属部门">
                    <el-cascader v-model="addForm.parent.id" placeholder="请选择所属部门"
                            :options="tree"
                            :props="{ checkStrictly: true ,label: 'name',value: 'id'}"
                            clearable >
                    </el-cascader>
                </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
                    keyword: ''         //过滤的条件
				},

				departments: [],        //列表绑定的数据
                employees: [],
                tree: [],               //部门树

                title: "新增",
				total: 0,               //总记录数
                currentPage: 1,         //当前页
                pageSize:6,
				listLoading: false,
				sels: [],               //列表选中列,批量删除用selection赋值给它
                selNode: [],

				addFormVisible: false,  //新增界面是否显示
				addLoading: false,      //提交忙等
				addFormRules: {         //表单校验规则
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
                    sn: [
                        { required: true, message: '请输入部门编号', trigger: 'blur' }
                    ]
				},
				//新增界面数据
				addForm: {
                    name: '',
                    sn: '',
                    dirPath: '',     //层级路径,无限极树选择后就有,不用手敲
                    state: 0,
                    manager: {},     //部门经理,需要其id值 动态查询更新到下拉列表
                    parent: {
                        id: []
                    }       //父部门,需要其id值动态查询更新
				}

			}
		},
		methods: {
            selChange(selNode){
                console.log('选中节点-----',selNode)
                console.log('当前正在编辑的节点----',this.addForm)
                this.selNode = selNode;
            },

            flush(){
                this.getDepartments();
            },

            //切换页码
			handleCurrentChange(cPage) {//用户点击的页码
			    console.log(cPage)
                this.currentPage = cPage;   //更新当前页
                this.getDepartments();      //分页查询列表
			},

			//获取部门列表
			getDepartments() {
				let para = {
                    currentPage: this.currentPage,    //当前页
                    pageSize: this.pageSize,
					keyword: this.filters.keyword     //搜索的关键词,可能是编号,也可能是名称
				};
				this.listLoading = true;        //开启页面忙等
				//NProgress.start();
				this.$http.post('/department',para).then((res) => {
				    console.log(res)
				    this.departments = res.data.list    //更新表格数据
                    this.total = res.data.total         //更新分页的总记录数
                    this.listLoading = false;
				}).catch(res=>{
                    this.$message.error("网络异常")
                });
			},

            //获取员工
            getEmployees(){
                this.$http.get("/emp/queryAll").then(res=>{
                    this.employees = res.data
                }).catch(res=>{
                    this.$message.error("网络异常")
                })
            },

            //获取部门树
            getTree(){
			    this.$http.get("/department/tree")
                    .then(res=>{
                        console.log("树",res.data)
                        this.tree = res.data
                    }).catch(res=>{
                        this.$message.error("网络异常")
                })
            },

			//删除
			handleDel: function (id) {
                console.log('要删除的id是---',id)
			    //判断要删除的部门有无子部门
                this.$http.get("/department/pid/"+id).then(res=>{
                    if (res.data.length){
                        this.$message({
                            message: "该部门存在子部门,不可直接删除",
                            type: "warning"
                        })
                    }else {
                        this.$confirm('确认删除该记录吗?', '提示', {
                            type: 'warning'
                        }).then(() => {
                            this.listLoading = true;

                            //发送删除请求
                            this.$http.delete("/department/"+id).then((res) => {
                                this.listLoading = false;
                                //NProgress.done();
                               if (res.data.success){
                                   this.$message({
                                       message: '删除成功',
                                       type: 'success'
                                   });
                               }else{
                                   this.$message({
                                       message: res.data.message,
                                       type: 'error'
                                   });
                               }
                                this.handleCurrentChange(1);
                            });
                        }).catch(() => {
                            this.$message.error("网络异常")
                        })
                    }
                })
			},
			//显示编辑界面
			handleEdit: function (row) {
			    this.title = '编辑';
			    console.log("编辑",row)
				this.addFormVisible = true;

                if(!row.parent){
                    row.parent = {id:[]}
                }
                if(!row.manager){
                    row.manager = {}
                }
                if(row.dirPath){
                    let arr = row.dirPath.substr(1).split("/");
                    if(arr.length > 0){
                        row.parent = {
                            id: arr.slice(0,arr.length-1).map(item=>parseInt(item))
                        }
                    }
                }
                //row是当前行实体对象,复制该对象,并赋值给addForm addForm和表单做了双向数据绑定
				this.addForm = Object.assign({}, row);
			},
			//显示新增界面,清空回显数据
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
                    name: '',
                    sn: '',
                    state: -1,
                    manager: {},
                    parent: {}
				};
			},
			/*//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editDepartment(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getDepartments();
							});
						});
					}
				});
			},*/
			//新增
			addSubmit: function () {
			    //表单校验 $refs  57行 ref="addForm"

				this.$refs.addForm.validate((valid) => {
                    //如果选的是当前节点
                    for(let i = 0;i<this.selNode.length;i++){
                        if(this.selNode[i]==this.addForm.id){
                            this.$message({
                                message: '上级部门不能选择自己或自己的子级部门',
                                type: 'warning'
                            });
                            valid = false;
                        }
                    }
				    //通过校验
					if (valid) {
					    //询问是否提交表单
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							//this.addLoading = true;
							//收集参数  将表单绑定的数据复制到另一个对象中作为备用参数
							let para = Object.assign({}, this.addForm);

							console.log('备用参数',para)

                            //整理数据
                            let idArr = para.parent.id; //取到的id是数组
							if (idArr.length > 0){      //id数组长度大于零,说明该新添部门不是一级部门,需要取数组最后一位作为该新添部门的id
                                para.parent.id = idArr[idArr.length-1]
                                para.dirPath = "/"+idArr.join("/")   //拼接父部门路径----------拼上去只有父级没有自己(服务器处理)
                            }else if(idArr.length == 0){    //应对没有选择部门的情况       ,回显数据:parent:{id:44}
                                para.parent = {}            //id数组长度为0,说明该新添部门是一级部门,传对象容器
                                para.dirPath = ''
                            }

							//整理层级路径
                            /*
                            添加时不知道自己的id,需要完成添加后,返回自增id
                            1.选择自己的所属部门/2/5
                            2.将/2/5作为dirPath提交给服务器
                            3.添加到数据库,但是缺少自己的id
                            4.拿到自增id 拼接到之前的/2/5
                            5.发起修改  67  --->/2/5/67

                            修改
                            1.选择自己的上级部门
                            2.将/2/5作为dirPath提交给服务器 同时携带了id
                            3.拿到自增id 拼接到之前的/2/5
                            4.发起修改
                             */

							this.$http.put("/department/saveOrUpdate",para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								//重置表单
								//this.$refs['addForm'].resetFields();
								//隐藏添加对话框
								this.addFormVisible = false;
								//重新查询列表,刷新到第一页
                                if (this.title == '新增'){
                                    this.handleCurrentChange(1);
                                }else if(this.title == '编辑'){
                                    this.getDepartments();
                                }

							});
						});
					}
				});
			},
            //选中某行,触发该方法
            selectRow: function (selection,row){
			    this.sels = selection;  //收集要删除的行数
                this.$http.get("/department/pid/"+row.id).then(res=>{
                    if (res.data.length){
                        this.$message({
                            message: "该部门存在子部门,不可直接删除",
                            type: "warning"
                        })
                        this.$refs.deptTable.toggleRowSelection(row,false)
                    }
                })
            },

			//批量删除
			batchRemove: function () {
			    //批量删除的集合:this.sels
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.patch("/department",ids).then((res) => {
						this.listLoading = false;
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.handleCurrentChange(1);
					});
				}).catch(() => {
                    this.$message.error("网络异常")
				});
			}
		},
		mounted() {//默认查询,组件一完成挂载,方法就会在这里调用
			this.getDepartments();
			this.getEmployees();
			this.getTree()
		}
	}

</script>

<style scoped>

</style>